package com.lwf.fatapi.config;

import cn.dev33.satoken.stp.StpInterface;
import com.lwf.fatapi.entities.SysPermission;
import com.lwf.fatapi.entities.SysRole;
import com.lwf.fatapi.entities.SysUserRole;
import com.lwf.fatapi.mapper.SysPermissionMapper;
import com.lwf.fatapi.mapper.SysRoleMapper;
import com.lwf.fatapi.mapper.SysUserRoleMapper;
import com.mybatisflex.core.query.QueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

import static com.lwf.fatapi.entity.table.SysUserRoleTableDef.SYS_USER_ROLE;

/**
 * SA-Token 权限接口实现类
 *
 * @author lwf
 */
@Component
public class StpInterfaceImpl implements StpInterface {

    @Autowired
    private SysUserRoleMapper userRoleMapper;

    @Autowired
    private SysRoleMapper roleMapper;

    @Autowired
    private SysPermissionMapper permissionMapper;

    /**
     * 返回一个账号所拥有的权限码集合
     */
    @Override
    public List<String> getPermissionList(Object loginId, String loginType) {
        // 根据用户ID查询权限
        Long userId = Long.valueOf(String.valueOf(loginId));

        // 查询用户角色
        List<SysUserRole> userRoles = userRoleMapper.selectListByQuery(
                QueryWrapper.create().where(SYS_USER_ROLE.USER_ID.eq(userId))
        );

        List<String> permissionList = new ArrayList<>();
        for (SysUserRole userRole : userRoles) {
            // 通过角色查询权限
            List<SysPermission> permissions = permissionMapper.selectPermissionsByRoleId(userRole.getRoleId());
            for (SysPermission permission : permissions) {
                permissionList.add(permission.getPermissionCode());
            }
        }

        return permissionList;
    }

    /**
     * 返回一个账号所拥有的角色标识集合
     */
    @Override
    public List<String> getRoleList(Object loginId, String loginType) {
        // 根据用户ID查询角色
        Long userId = Long.valueOf(String.valueOf(loginId));

        // 查询用户角色
        List<SysUserRole> userRoles = userRoleMapper.selectListByQuery(
                QueryWrapper.create().where(SYS_USER_ROLE.USER_ID.eq(userId))
        );

        List<String> roleList = new ArrayList<>();
        for (SysUserRole userRole : userRoles) {
            SysRole role = roleMapper.selectOneById(userRole.getRoleId());
            if (role != null) {
                roleList.add(role.getRoleCode());
            }
        }

        return roleList;
    }
}
